<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Coze 智能体通信界面</title>
    <style>
        body { font-family: sans-serif; margin: 20px; }
        #messages { margin-top: 20px; padding: 10px; border: 1px solid #ccc; height: 200px; overflow-y: scroll; }
    </style>
</head>
<body>
    <h2>输入消息并发送</h2>
    <input type="text" id="messageInput" placeholder="请输入消息" style="width:300px;">
    <button onclick="sendMessage()">发送</button>
    
    <div id="messages"></div>
    
    <script>
        // 注意：确保这里的地址与 server.py 中的地址一致
        const ws = new WebSocket("ws://127.0.0.1:8001");  

        ws.onopen = function() {
            addMessage("[系统] WebSocket 已连接");
        };

        ws.onmessage = function(event) {
            addMessage("[服务器] " + event.data);
        };

        ws.onerror = function(event) {
            addMessage("[错误] " + event);
        };

        ws.onclose = function() {
            addMessage("[系统] WebSocket 连接已关闭");
        };

        function sendMessage() {
            const input = document.getElementById("messageInput");
            const msg = input.value.trim();
            if(msg !== ""){
                // 将用户输入封装为 JSON 格式发送
                ws.send(JSON.stringify({ input: msg }));
                addMessage("[客户端] " + msg);
                input.value = "";
            }
        }

        function addMessage(msg) {
            const messagesDiv = document.getElementById("messages");
            const p = document.createElement("p");
            p.innerText = msg;
            messagesDiv.appendChild(p);
        }
    </script>
</body>
</html>